package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@SuppressWarnings("all")
public class CourseServiceImpl implements CourseService {
    @Autowired
    CourseMapper courseMapper;

    @Override
    public PageResult<Course> listCourses(CourseDTO courseDto) {
        PageHelper.startPage(courseDto.getPage(), courseDto.getPageSize());
        List<Course> courses = courseMapper.selectByPage(courseDto);
        Page< Course> page = (Page<Course>) courses;
        return PageResult.<Course>builder()
                .total(page.getTotal())
                .rows(courses)
                .build();
    }

    @Override
    public void addCourse(Course course) {
        boolean hasNull = BeanUtil.hasNullField(course, "id","description","updateTime","createTime" );
        if (hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public void deleteCourse(Integer id) {
        if (Objects.isNull(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        courseMapper.deleteById(id);
    }

    @Override
    public void updateCourse(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }

    @Override
    public Course getById(Integer id) {
        if (Objects.isNull(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return courseMapper.getById(id);
    }

    @Override
    public List<Course> getAllCourses() {

        return courseMapper.getAllCourses();
    }

    @Override
    public List<Course> getBySubject(String subject) {
        if(ObjectUtils.isEmpty( subject)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return courseMapper.getBySubject(subject);
    }
}
